import {
	baseUrl
} from '@/utils/setting.js'
export const fileToBase64 = (file) => {
	if (!file) return null;
	return new Promise((resolve) => {
		let reader = new FileReader();
		reader.onload = (ev) => resolve(ev.target.result);
		reader.onerror = () => resolve(null);
		reader.readAsDataURL(file);
	});
};
// 添加缓存机制
const imageCache = {};

export const uploadToImg = async (img) => {
	if (imageCache[img]) {
		return imageCache[img];
	}

	try {
		const response = await fetch(baseUrl + "admin/Img?img=" + img, {
			headers: {
				Authorization: `${localStorage.getItem("token")}`,
			},
		});
		if (response.ok) {
			const blob = await response.blob();
			const objectUrl = URL.createObjectURL(blob);
			imageCache[img] = objectUrl; // 缓存结果
			return objectUrl;
		}
	} catch (error) {
		console.error("获取图片时出错:", error);
	}
};